package com.lb.shopguide.ui.fragment.guide.goods;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGoodsList;
import com.lb.shopguide.base.BasePageFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.goods.GoodsInListBean;
import com.lb.shopguide.entity.goods.GoodsTypeBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogSelectSku;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by kang on 2017/6/7.
 */

public class FragmentGoodsList extends BasePageFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;


    private AdapterGoodsList mAdapterGoods;
    private List<GoodsInListBean> mGoodsList;
    private List<GoodsInListBean> mSelectedGoodsList;

    private GoodsTypeBean mGoodsTypeBean;
    private int goodsSelectType;


    public static FragmentGoodsList newInstance(GoodsTypeBean bean, int goodsSelectType) {
        FragmentGoodsList fragmentGoodsList = new FragmentGoodsList();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.GOODS_TYPE_BEAN, bean);
        bundle.putSerializable(AppConstant.GOODS_SELECT_TYPE, goodsSelectType);
        fragmentGoodsList.setArguments(bundle);
        return fragmentGoodsList;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_goods_list;
    }

    @Override
    public void initData() {
        mGoodsList = new ArrayList<>();
        mSelectedGoodsList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GOODS_TYPE_BEAN)) {
            mGoodsTypeBean = (GoodsTypeBean) bundle.getSerializable(AppConstant.GOODS_TYPE_BEAN);
        }
        if (bundle.containsKey(AppConstant.GOODS_SELECT_TYPE)) {
            goodsSelectType = bundle.getInt(AppConstant.GOODS_SELECT_TYPE);
        }

        sendRequestForPageData();
    }

    @Override
    public void initView() {

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有商品");
//        tvEmpty.setOnClickListener(this);

        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterGoods = new AdapterGoodsList(R.layout.item_goods_management, mGoodsList);
        mRecyclerView.setAdapter(mAdapterGoods);
        mAdapterGoods.setOnLoadMoreListener(this, mRecyclerView);
        mAdapterGoods.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHAT) {
                    GoodsInListBean bean = mGoodsList.get(position);
                    bean.setChecked(!bean.isChecked());
                    mAdapterGoods.notifyDataSetChanged();
                } else if (goodsSelectType == AppConstant.GOODS_SELECT_IN_MANAGEMENT) {
                    //进入商品详情
                    ((FragmentSelectGoods) getParentFragment()).start(FragmentGoodsDetail.newInstance(mGoodsList.get(position).getProductCode(), AppConstant.GOODS_DETAIL_NORMAL));
                } else if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHECKOUT) {
                    //弹出选择sku
                    if (mGoodsList.size() > position) {
                        mSelectedGoodsList.add(mGoodsList.get(position));
                        DialogSelectSku dialogSelectSku = DialogSelectSku.getDialogSelectSku(mGoodsList.get(position));
                        dialogSelectSku.show(getParentFragment().getFragmentManager(), FragmentGoodsList.class.getSimpleName());
                    }
                }
            }
        });

        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).marginProvider(mAdapterGoods).paintProvider(mAdapterGoods).build());

//        mAdapterOrderList.setOnActionClickListener(mOnActionClickListener);
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        if (mAdapterGoods != null) {
            mAdapterGoods.loadMoreComplete();
        }
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentGoodsList.class.getName();
    }

    @Override
    public void onLoadMoreRequested() {
        if (curPageBean.isHasNextPage()) {
            loadMore();
        } else {
            if (getUserVisibleHint()) {
                ToastUtils.showShort("没有更多了");
            }
            mAdapterGoods.loadMoreEnd(true);
        }
    }

    public void refresh() {
        mGoodsList = new ArrayList<>();
        super.refresh();
    }


    private void bindEmpty() {
        mGoodsList.clear();
        mAdapterGoods.setNewData(mGoodsList);

        mNoData = true;
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mAdapterGoods.setEnableLoadMore(false);
        if (mError) {
            mAdapterGoods.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterGoods.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    public List<GoodsInListBean> getSelectedGoodsList() {
        for (GoodsInListBean bean : mGoodsList) {
            if (bean.isChecked()) {
                bean.setStoreCode(mUserConfigManager.getStoreCode());
                mSelectedGoodsList.add(bean);
            }
        }
        return mSelectedGoodsList;
    }

//    public String getGoodsTypeCode() {
//        return mGoodsTypeBean.getZoneCode();
//    }

    @Override
    public void sendRequestForPageData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    curPageBean = JsonUtil.getPageBeanFromMap(response.getReturnContent());
                    JsonArray jsonGoods = curPageBean.getList();
                    if (jsonGoods.size() != 0) {
                        for (JsonElement obj : jsonGoods) {
                            GoodsInListBean bean = JsonUtil.getGson().fromJson(obj, GoodsInListBean.class);
                            mGoodsList.add(bean);
                        }
                        mAdapterGoods.setNewData(mGoodsList);
                    } else {
                        bindEmpty();
                    }
                    finishRefresh();
                }
            }
        };
        ApiMethodGuide.getGoodsListByCondition(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getStoreCode(),
                mGoodsTypeBean.getTypeCode(), null, pageNum, pageSize, this, FragmentEvent.DESTROY_VIEW);
    }
}
